/**
 * API 工具类
 */
import axios from 'axios'
import config from '@/config'

// 创建axios实例
const api = axios.create({
  baseURL: config.REMOTE_URL,
  timeout: config.TIMEOUT,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    // 添加token
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    return response.data
  },
  (error) => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          // 未授权，跳转到登录页
          localStorage.removeItem('token')
          window.location.href = '/login'
          break
        case 403:
          console.error('权限不足')
          break
        case 404:
          console.error('请求的资源不存在')
          break
        case 500:
          console.error('服务器内部错误')
          break
        default:
          console.error('网络错误')
      }
    }
    return Promise.reject(error)
  }
)

// 登录API
export const loginAPI = {
  // 用户登录
  login: (data) => {
    return api.post('/api/auth/login', data)
  },
  
  // 获取用户信息
  getUserInfo: () => {
    return api.get('/api/auth/user')
  },
  
  // 退出登录
  logout: () => {
    return api.post('/api/auth/logout')
  }
}

// 模拟登录API（用于开发测试）
export const mockLoginAPI = {
  login: (data) => {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        // 模拟验证用户名密码
        if (data.username === 'admin' && data.password === '123456') {
          resolve({
            code: 200,
            message: '登录成功',
            data: {
              token: 'mock_token_' + Date.now(),
              user: {
                id: 1,
                username: 'admin',
                nickname: '管理员',
                avatar: '',
                roles: ['admin']
              }
            }
          })
        } else {
          reject({
            code: 401,
            message: '用户名或密码错误'
          })
        }
      }, 1000)
    })
  },
  
  getUserInfo: () => {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve({
          code: 200,
          data: {
            id: 1,
            username: 'admin',
            nickname: '管理员',
            avatar: '',
            roles: ['admin']
          }
        })
      }, 500)
    })
  },
  
  logout: () => {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve({
          code: 200,
          message: '退出成功'
        })
      }, 500)
    })
  }
}

export default api 